<!DOCTYPE html>
<title>RTCDataChannel Content Browser Test</title>
<script type="text/javascript" src="webrtc_test_utilities.js"></script>
<script>

// Tests that an RTCDataChannel with event handlers is not garbage-collected
// prematurely.
async function testDataChannelGC() {
  var pc1 = new RTCPeerConnection();
  var pc2 = new RTCPeerConnection();

  var iceCandidateHandler = function(rpc) {
    return function(e) {
      if (e.candidate) {
        rpc.addIceCandidate(e.candidate);
      }
    }
  };

  pc1.addEventListener("icecandidate", iceCandidateHandler(pc2));
  pc2.addEventListener("icecandidate", iceCandidateHandler(pc1));

  var messagesReceived = 0;
  var dc1 = pc1.createDataChannel(null);
  const resultPromise = new Promise(resolve => {
    dc1.addEventListener("open", function(e) {
      console.log("dc1/open event");
      var messagesToSend = 6;
      var messagesSent = 0;
      var id = setInterval(function() {
        if (messagesReceived < messagesToSend) {
          messagesSent++;
          dc1.send("message #" + messagesSent);
        } else if (messagesReceived == messagesToSend) {
          clearInterval(id);
          resolve();
          return;
        }
        if (messagesSent == 3) {
          gc();  // Force garbage collection (requires: --js-flags="--expose-gc").
        }
      }, 10);
    });
  });

  pc2.addEventListener("datachannel", function(e) {
    console.log("pc2/datachannel event");
    var dc2 = e.channel;
    dc2.addEventListener("message", function(e) {
      console.log("dc2/message event: " + JSON.stringify(e.data));
      messagesReceived++;
    });
  });

  console.log("creating offer");
  const sdp1 = await new Promise((resolve, reject) => {
    pc1.createOffer(resolve, reject);
  });
  pc1.setLocalDescription(sdp1);
  await new Promise((resolve, reject) => {
    pc2.setRemoteDescription(sdp1, resolve, reject);
  });
  console.log("creating answer");
  const sdp2 = await new Promise((resolve, reject) => {
    pc2.createAnswer(resolve, reject);
  });
  pc1.setRemoteDescription(sdp2);
  pc2.setLocalDescription(sdp2);

  await resultPromise;
  return logSuccess();
}
</script>
